<template>
  <div class="user-profile">
    <el-row :gutter="20">
      <!-- 左侧个人信息卡片 -->
      <el-col :span="8">
        <el-card class="profile-card">
          <div class="avatar-container">
            <el-avatar
              :size="120"
              :src="userInfo.avatar || defaultAvatar"
              @error="handleAvatarError"
            />
            <div class="avatar-upload">
              <el-upload
                class="avatar-uploader"
                :action="`${API_BASE_URL}/users/avatar/`"
                :headers="uploadHeaders"
                :show-file-list="false"
                :before-upload="beforeAvatarUpload"
                :on-success="handleAvatarSuccess"
                :on-error="handleAvatarError"
              >
                <el-button type="primary" size="small">
                  <el-icon><Camera /></el-icon>
                  更换头像
                </el-button>
              </el-upload>
            </div>
          </div>
          
          <div class="user-info">
            <h2>{{ userInfo.username }}</h2>
            <p class="user-role">
              <el-tag size="small" type="success">{{ userInfo.role || '普通用户' }}</el-tag>
            </p>
            <p class="join-date">加入时间：{{ formatDate(userInfo.join_date) }}</p>
          </div>

          <div class="user-stats">
            <div class="stat-item">
              <h3>{{ userInfo.document_count || 0 }}</h3>
              <p>文档数</p>
            </div>
            <div class="stat-item">
              <h3>{{ formatSize(userInfo.storage_used || 0) }}</h3>
              <p>已用空间</p>
            </div>
            <div class="stat-item">
              <h3>{{ userInfo.share_count || 0 }}</h3>
              <p>分享数</p>
            </div>
          </div>
        </el-card>
      </el-col>

      <!-- 右侧信息编辑区域 -->
      <el-col :span="16">
        <el-card>
          <template #header>
            <div class="card-header">
              <el-tabs v-model="activeTab">
                <el-tab-pane label="基本信息" name="basic">
                  <template #label>
                    <el-icon><User /></el-icon>基本信息
                  </template>
                </el-tab-pane>
                <el-tab-pane label="安全设置" name="security">
                  <template #label>
                    <el-icon><Lock /></el-icon>安全设置
                  </template>
                </el-tab-pane>
                <el-tab-pane label="通知设置" name="notifications">
                  <template #label>
                    <el-icon><Bell /></el-icon>通知设置
                  </template>
                </el-tab-pane>
              </el-tabs>
            </div>
          </template>

          <!-- 基本信息表单 -->
          <el-form
            v-if="activeTab === 'basic'"
            ref="basicForm"
            :model="userForm"
            :rules="basicRules"
            label-width="100px"
          >
            <el-form-item label="用户名" prop="username">
              <el-input v-model="userForm.username" disabled />
            </el-form-item>
            <el-form-item label="昵称" prop="nickname">
              <el-input v-model="userForm.nickname" placeholder="请输入昵称" />
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="userForm.email" placeholder="请输入邮箱">
                <template #append>
                  <el-button v-if="!userInfo.email_verified" type="primary" @click="verifyEmail">
                    验证邮箱
                  </el-button>
                  <el-tag v-else type="success">已验证</el-tag>
                </template>
              </el-input>
            </el-form-item>
            <el-form-item label="手机号" prop="phone">
              <el-input v-model="userForm.phone" placeholder="请输入手机号">
                <template #append>
                  <el-button v-if="!userInfo.phone_verified" type="primary" @click="verifyPhone">
                    验证手机
                  </el-button>
                  <el-tag v-else type="success">已验证</el-tag>
                </template>
              </el-input>
            </el-form-item>
            <el-form-item label="个人简介" prop="bio">
              <el-input
                v-model="userForm.bio"
                type="textarea"
                rows="4"
                placeholder="请输入个人简介"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="saveBasicInfo">保存修改</el-button>
              <el-button @click="resetBasicInfo">重置</el-button>
            </el-form-item>
          </el-form>

          <!-- 安全设置表单 -->
          <el-form
            v-if="activeTab === 'security'"
            ref="securityForm"
            :model="securityForm"
            :rules="securityRules"
            label-width="100px"
          >
            <el-form-item label="原密码" prop="oldPassword">
              <el-input
                v-model="securityForm.oldPassword"
                type="password"
                placeholder="请输入原密码"
                show-password
              />
            </el-form-item>
            <el-form-item label="新密码" prop="newPassword">
              <el-input
                v-model="securityForm.newPassword"
                type="password"
                placeholder="请输入新密码"
                show-password
              />
            </el-form-item>
            <el-form-item label="确认密码" prop="confirmPassword">
              <el-input
                v-model="securityForm.confirmPassword"
                type="password"
                placeholder="请再次输入新密码"
                show-password
              />
            </el-form-item>
            <el-divider>登录保护</el-divider>
            <el-form-item label="两步验证">
              <el-switch v-model="securityForm.twoFactorAuth" />
            </el-form-item>
            <el-form-item label="登录通知">
              <el-switch v-model="securityForm.loginNotification" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="saveSecuritySettings">保存设置</el-button>
              <el-button @click="resetSecuritySettings">重置</el-button>
            </el-form-item>
          </el-form>

          <!-- 通知设置表单 -->
          <el-form
            v-if="activeTab === 'notifications'"
            ref="notificationForm"
            :model="notificationForm"
            label-width="100px"
          >
            <el-form-item label="系统通知">
              <el-switch v-model="notificationForm.systemNotifications" />
            </el-form-item>
            <el-form-item label="邮件通知">
              <el-switch v-model="notificationForm.emailNotifications" />
            </el-form-item>
            <el-form-item label="通知类型">
              <el-checkbox-group v-model="notificationForm.notificationTypes">
                <el-checkbox label="document_share">文档分享</el-checkbox>
                <el-checkbox label="document_update">文档更新</el-checkbox>
                <el-checkbox label="system_message">系统消息</el-checkbox>
                <el-checkbox label="security_alert">安全提醒</el-checkbox>
              </el-checkbox-group>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="saveNotificationSettings">保存设置</el-button>
              <el-button @click="resetNotificationSettings">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import {
  User,
  Lock,
  Bell,
  Camera
} from '@element-plus/icons-vue'
import http from '../utils/axios'  // 使用配置好的axios实例

const API_BASE_URL = `${import.meta.env.VITE_API_URL}/api`
const defaultAvatar = 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'

// 用户信息
const userInfo = ref({
  username: 'admin',
  role: '管理员',
  join_date: '2024-03-01',
  email_verified: true,
  phone_verified: false,
  document_count: 15,
  storage_used: 1024 * 1024 * 500, // 500MB
  share_count: 8
})

// 上传头像的请求头
const uploadHeaders = {
  'Authorization': `Bearer ${localStorage.getItem('access_token')}`
}

// 当前激活的标签页
const activeTab = ref('basic')

// 基本信息表单
const userForm = reactive({
  username: userInfo.value.username,
  nickname: '',
  email: '',
  phone: '',
  bio: ''
})

// 安全设置表单
const securityForm = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: '',
  twoFactorAuth: false,
  loginNotification: true
})

// 通知设置表单
const notificationForm = reactive({
  systemNotifications: true,
  emailNotifications: true,
  notificationTypes: ['document_share', 'security_alert']
})

// 表单校验规则
const basicRules = {
  email: [
    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ]
}

const securityRules = {
  oldPassword: [
    { required: true, message: '请输入原密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请再次输入新密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== securityForm.newPassword) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 头像上传相关方法
const beforeAvatarUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('上传头像图片只能是图片格式!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('上传头像图片大小不能超过 2MB!')
    return false
  }
  return true
}

// 获取用户信息
const fetchUserInfo = async () => {
  try {
    const response = await http.get('/users/profile/')
    userInfo.value = response.data
    // 更新表单数据
    userForm.username = response.data.username
    userForm.nickname = response.data.nickname
    userForm.email = response.data.email
    userForm.phone = response.data.phone
    userForm.bio = response.data.bio
  } catch (error) {
    console.error('获取用户信息失败:', error)
    ElMessage.error('获取用户信息失败')
  }
}

// 保存基本信息
const saveBasicInfo = async () => {
  try {
    await http.put('/users/profile/', userForm)
    ElMessage.success('保存成功')
    fetchUserInfo()
  } catch (error) {
    console.error('保存基本信息失败:', error)
    ElMessage.error('保存失败')
  }
}

// 保存安全设置
const saveSecuritySettings = async () => {
  try {
    await http.put('/users/security/', securityForm)
    ElMessage.success('保存成功')
  } catch (error) {
    console.error('保存安全设置失败:', error)
    ElMessage.error('保存失败')
  }
}

// 保存通知设置
const saveNotificationSettings = async () => {
  try {
    await http.put('/users/notifications/', notificationForm)
    ElMessage.success('保存成功')
  } catch (error) {
    console.error('保存通知设置失败:', error)
    ElMessage.error('保存失败')
  }
}

// 验证邮箱
const verifyEmail = async () => {
  try {
    await http.post('/users/verify-email/')
    ElMessage.success('验证邮件已发送')
  } catch (error) {
    console.error('发送验证邮件失败:', error)
    ElMessage.error('发送验证邮件失败')
  }
}

// 验证手机
const verifyPhone = async () => {
  try {
    await http.post('/users/verify-phone/')
    ElMessage.success('验证码已发送')
  } catch (error) {
    console.error('发送验证码失败:', error)
    ElMessage.error('发送验证码失败')
  }
}

// 处理头像上传成功
const handleAvatarSuccess = (response) => {
  ElMessage.success('头像上传成功')
  userInfo.value.avatar = response.avatar_url
}

// 处理头像上传失败
const handleAvatarError = (error) => {
  console.error('头像上传失败:', error)
  ElMessage.error('头像上传失败')
}

// 格式化日期
const formatDate = (date) => {
  if (!date) return ''
  return new Date(date).toLocaleDateString()
}

// 格式化文件大小
const formatSize = (bytes) => {
  if (!bytes) return '0 B'
  const units = ['B', 'KB', 'MB', 'GB', 'TB']
  let size = bytes
  let unitIndex = 0
  while (size >= 1024 && unitIndex < units.length - 1) {
    size /= 1024
    unitIndex++
  }
  return `${size.toFixed(2)} ${units[unitIndex]}`
}

// 重置基本信息
const resetBasicInfo = () => {
  userForm.nickname = userInfo.value.nickname || ''
  userForm.email = userInfo.value.email || ''
  userForm.phone = userInfo.value.phone || ''
  userForm.bio = userInfo.value.bio || ''
}

// 重置安全设置
const resetSecuritySettings = () => {
  securityForm.oldPassword = ''
  securityForm.newPassword = ''
  securityForm.confirmPassword = ''
  securityForm.twoFactorAuth = userInfo.value.two_factor_auth || false
  securityForm.loginNotification = userInfo.value.login_notification || false
}

// 重置通知设置
const resetNotificationSettings = () => {
  notificationForm.systemNotifications = userInfo.value.system_notifications || false
  notificationForm.emailNotifications = userInfo.value.email_notifications || false
  notificationForm.notificationTypes = userInfo.value.notification_types || []
}

// 在组件挂载时获取用户信息
onMounted(() => {
  fetchUserInfo()
})
</script>

<style scoped>
.user-profile {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.profile-card {
  text-align: center;
  padding: 20px;
}

.avatar-container {
  margin-bottom: 20px;
}

.avatar-upload {
  margin-top: 16px;
}

.user-info {
  margin-bottom: 24px;
}

.user-info h2 {
  margin: 16px 0 8px;
  font-size: 20px;
  color: #303133;
}

.user-role {
  margin: 8px 0;
}

.join-date {
  color: #909399;
  font-size: 14px;
}

.user-stats {
  display: flex;
  justify-content: space-around;
  margin-top: 24px;
  border-top: 1px solid #EBEEF5;
  padding-top: 24px;
}

.stat-item h3 {
  margin: 0;
  font-size: 20px;
  color: #303133;
}

.stat-item p {
  margin: 8px 0 0;
  font-size: 14px;
  color: #909399;
}

.el-tabs {
  margin-bottom: -16px;
}

:deep(.el-tabs__nav) {
  border: none;
}

:deep(.el-tabs__item) {
  display: flex;
  align-items: center;
  gap: 4px;
}

.el-divider {
  margin: 24px 0;
}

.el-form {
  max-width: 600px;
  margin: 24px auto;
}
</style> 